package models

import (
	"aifuture.cloud/pkg/e"
	"github.com/jinzhu/gorm"
)

type User struct {
	// 用户id
	ID uint64 `gorm:"column:id" json:"id"`
	// 用户名
	UserName string `gorm:"column:user_name" json:"user_name"`
	// 密码
	Password string `gorm:"column:password" json:"password"`
	// 电话
	Phone string `gorm:"column:phone" json:"phone"`
	// 邮箱
	Email string `gorm:"column:email" json:"email"`
	// 平台id
	PlatformID uint64 `gorm:"column:platform_id" json:"platform_id"`
	// 注册时间
	RegisterTime DbTime `gorm:"column:register_time" json:"register_time"`
	// 更新时间
	UpdateTime DbTime `gorm:"column:update_time" json:"update_time"`
}

func (User) TableName() string {
	return "users"
}

func CreateUser(data *User) (uint64, e.FResult) {
	db := db.Begin()
	// 写入用户
	err := db.Debug().
		Select("user_name", "password", "phone", "email", "platform_id", "register_time").
		Create(data).Error
	if err != nil {
		db.Rollback()
		return 0, e.FResult_ERROR
	}
	db.Commit()
	return data.ID, e.FResult_OK
}

func GetUserById(userId uint64) (*User, e.FResult) {
	var data User
	err := db.Model(&User{}).Debug().Where("id = ?", userId).First(&data).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, e.FResult{ErrCode: e.ERROR, ErrMsg: "用户不存在"}
		} else {
			return nil, e.FResult_ERROR
		}
	} else {
		return &data, e.FResult_OK
	}
}

func GetUserByUserName(username string) (*User, e.FResult) {
	var data User
	err := db.Model(&User{}).Debug().Where("user_name=? ", username).First(&data).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, e.FResult{ErrCode: e.ERROR, ErrMsg: "用户不存在"}
		} else {
			return nil, e.FResult_ERROR
		}
	} else {
		return &data, e.FResult_OK
	}
}

func GetUserByPhone(phone string) (*User, e.FResult) {
	var data User
	err := db.Model(&data).Debug().Where("phone=? ", phone).First(&data).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, e.FResult{ErrCode: e.ERROR, ErrMsg: "用户不存在"}
		} else {
			return nil, e.FResult_ERROR
		}
	} else {
		return &data, e.FResult_OK
	}
}

func GetUserByEmail(email string) (*User, e.FResult) {
	var data User
	err := db.Model(&data).Debug().Where("email=? ", email).First(&data).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, e.FResult{ErrCode: e.ERROR, ErrMsg: "用户不存在"}
		} else {
			return nil, e.FResult_ERROR
		}
	} else {
		return &data, e.FResult_OK
	}
}

func UpdateUserById(userId uint64, datas map[string]interface{}) e.FResult {
	err := db.Model(&User{}).Debug().Where("id =? ", userId).Updates(datas).Error
	if err != nil {
		return e.FResult_ERROR
	} else {
		return e.FResult_OK
	}
}
